from rest_framework.pagination import PageNumberPagination

from djangoProject1.serializers import DynamicFieldsModelSerializer
from user.models import User, Role, Clazz, Language, Menu, Func, Task, Module, Permission, TaskUser
from rest_framework import serializers

class StudentSerializer(serializers.ModelSerializer):
    clazz_name = serializers.CharField(source='clazz.name', read_only=True)

    class Meta:
        model = User
        fields = ['id', 'name', 'email', 'date_joined', 'is_active', 'clazz', 'clazz_name']
        read_only_fields = ['id', 'register_time']

class UserSerializer(DynamicFieldsModelSerializer):

    class Meta:
        model = User
        exclude = ['groups', 'user_permissions']

    def create(self, validated_data):

        return User.objects.create_user(**validated_data)


class RoleSerializer(DynamicFieldsModelSerializer):

    class Meta:
        model = Role
        fields = '__all__'


class UserSerializers(DynamicFieldsModelSerializer):

    role = serializers.ReadOnlyField(source='role.name')

    class Meta:
        model = User
        exclude = ['groups', 'user_permissions',]


class ClazzSerializer(DynamicFieldsModelSerializer):

    class Meta:
        model = Clazz
        fields = '__all__'



class UserStatusSerializer(DynamicFieldsModelSerializer):
    class Meta:
        model = User
        fields = ['is_active']


class UserDeleteSerializer(DynamicFieldsModelSerializer):

    class Meta:
        model = User
        fields = ['is_delete']


class MenuSerializer(DynamicFieldsModelSerializer):

    class Meta:
        model = Menu
        fields = '__all__'


class ModuleSerializer(DynamicFieldsModelSerializer):
    langName = serializers.CharField(source='language.name',read_only=True)
    status = serializers.BooleanField(source='is_active',read_only=True)
    creator = serializers.CharField(source='user.username',read_only=True)
    language_id = serializers.PrimaryKeyRelatedField(
        queryset=Language.objects.filter(is_delete=False, is_active=True),
        source='language',

    )
    sort = serializers.IntegerField(default=0)

    class Meta:
        model = Module
        fields = [
            'id', 'name', 'description', 'create_time', 'update_time',
            'status', 'langName', 'creator', 'language_id', 'sort','is_active'
        ]
        read_only_fields = ['create_time', 'update_time', 'creator']


class LanguageSerializers(DynamicFieldsModelSerializer):
    class Meta:
        model = Language
        fields = ['id', 'name', 'description']


class CustomPageNumberPagination(PageNumberPagination):
    page_size_query_param = "rows"  # 允许客户端通过rows参数控制每页数量
    max_page_size = 100  # 最大每页数量限制


class LanguageSerializer(serializers.ModelSerializer):
    pagination_class = CustomPageNumberPagination
    class Meta:
        model = Language
        fields = '__all__'
        read_only_fields = ('create_time', 'update_time', 'delete_time', 'user')

    def validate_name(self, value):
        # 获取当前实例（更新操作时存在）
        instance = getattr(self, 'instance', None)

        # 验证名称唯一性（排除已删除的和当前实例）
        qs = Language.objects.filter(name=value, is_delete=False)
        if instance:
            qs = qs.exclude(id=instance.id)

        if qs.exists():
            raise serializers.ValidationError("该语言名称已存在")
        return value


class MenuSerializer(DynamicFieldsModelSerializer):

    class Meta:
        model = Menu
        fields = '__all__'


class FuncSerializer(DynamicFieldsModelSerializer):

    class Meta:
        model = Func
        fields = '__all__'


class ClazzSerializers(DynamicFieldsModelSerializer):
    studentCount = serializers.SerializerMethodField()

    class Meta:
        model = Clazz
        fields = '__all__'
        read_only_fields = ['creator']  # 让 creator 字段为只读（前端不能提交）

    def get_studentCount(self, obj):
        # 统计关联学生数量（不包含被软删除的用户）
        return obj.users.filter(is_delete=False).count()


class PermissionSerializer(DynamicFieldsModelSerializer):

    class Meta:
        model = Permission
        fields = '__all__'
# 序列化器

class TaskManageSerializer(DynamicFieldsModelSerializer):
    # 把id设置为只写创建的时候写入
    language_id = serializers.IntegerField(write_only=True)  # 直接接收ID
    module_id = serializers.IntegerField(write_only=True)
    # 把字段设置为只读去读两个模块里的数据
    lang_name = serializers.CharField(source='language.name', read_only=True)
    module_name = serializers.CharField(source='module.name', read_only=True)

    # 添加只读的creator字段展示
    creator = serializers.SerializerMethodField()

    class Meta:
        model = Task
        fields = [
            'id', 'title', 'completed', 'task_time',
            'create_time', 'lang_name', 'module_name',
            'language_id', 'module_id','creator','language', 'module'
        ]
        extra_kwargs = {
            'title': {'required': True},
            'completed': {'required': True},
            'task_time': {'required': False}
        }

    def get_creator(self, obj):
        # 获取第一个关联用户的用户名（根据您的TaskUser模型）
        task_user = obj.taskuser_set.order_by('id').first()
        return task_user.user.name if task_user else None

    def create(self, validated_data):
        # 手动处理外键关系
        validated_data['language'] = Language.objects.get(id=validated_data.pop('language_id'))
        validated_data['module'] = Module.objects.get(id=validated_data.pop('module_id'))
        return super().create(validated_data)

    # 在序列化器中添加更新方法
    def update(self, instance, validated_data):
        # 手动处理外键关系
        if 'language_id' in validated_data:
            instance.language = Language.objects.get(id=validated_data.pop('language_id'))
        if 'module_id' in validated_data:
            instance.module = Module.objects.get(id=validated_data.pop('module_id'))
        return super().update(instance, validated_data)
    # 添加这两个字段确保编辑时能获取完整数据
    language = serializers.PrimaryKeyRelatedField(
        queryset=Language.objects.all(),
        required=False,
        allow_null=True
    )
    module = serializers.PrimaryKeyRelatedField(
        queryset=Module.objects.all(),
        required=False,
        allow_null=True
    )


class ClassCountSerializer(serializers.ModelSerializer):
    studentCount = serializers.SerializerMethodField()

    class Meta:
        model = Clazz
        fields = ['name', 'studentCount']

    def get_studentCount(self, obj):
        # 统计每个班级的学生数量（不包括被删除的用户）
        return obj.users.filter(is_delete=False).count()


class TaskCompletionSerializer(serializers.ModelSerializer):
    clazz_name = serializers.CharField(source="name")
    total_users = serializers.IntegerField()
    completed_tasks = serializers.IntegerField()

    class Meta:
        model = Clazz

    def to_representation(self, instance):
        # 完成情况计算逻辑
        result = super().to_representation(instance)
        total_tasks = instance.taskuser_set.count()
        completed_tasks = instance.taskuser_set.filter(status=5).count()  # status=5表示已完成
        result['completionRate'] = (completed_tasks / total_tasks) * 100 if total_tasks else 0
        return result


class DifficultyLevelSerializer(serializers.Serializer):
    difficulty = serializers.CharField()
    taskCount = serializers.IntegerField()


class TaskStatusSerializer(serializers.Serializer):
    status = serializers.CharField()
    taskCount = serializers.IntegerField()


# 创建学生管理序列化器
class StudentManageSerializer(serializers.ModelSerializer):
    # 引入外键
    clazz_name = serializers.CharField(source='clazz.name', read_only=True)
    date_joined = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)

    class Meta:
        model = User
        fields = [
            'id', 'name', 'username', 'email',
            'date_joined', 'is_active', 'clazz_name'
        ]
        extra_kwargs = {
            'name': {'required': True},
            'username': {'required': True},
            'email': {'required': False}
        }


class StudentCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['name', 'username', 'email', 'password', 'clazz']
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def create(self, validated_data):
        user = User.objects.create_user(
            username=validated_data['username'],
            password=validated_data['password'],
            name=validated_data['name'],
            email=validated_data.get('email', ''),
            clazz=validated_data.get('clazz')
        )
        return user